package sfeir.ergosum;

import java.util.ArrayList;
import java.util.List;

import sfeir.ergosum.dao.RemoteProvider;
import sfeir.ergosum.dao.DatabaseConnection;
import sfeir.ergosum.dao.DatabaseProvider;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class AddContactSMSMailActivity extends ListActivity {
    private Cursor managedCursor;
    private List<String> listAlias;
    private List<String> listKey;
    private ListAdapter mAdapter;
    final Handler mHandler = new Handler();

    final Runnable invalidContact = new Runnable() {
        public void run() {
            Toast.makeText(AddContactSMSMailActivity.this,
                    "Ce contact est invalide", 3000).show();

        }
    };

    final Runnable regenList = new Runnable() {
        public void run() {
            onCreate(null);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent i = getIntent();
        if (i.hasExtra("code") == true) {
            String key = i.getStringExtra("code");
            RemoteProvider dao = new RemoteProvider(new DatabaseConnection(this));
            dao.addContactBySpreadsheet(key, i.getStringExtra("alias"));

            Intent in = new Intent(this, HiveActivity.class);
            in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            this.startActivity(in);
            this.finish();
        }
        setContentView(R.layout.add_contact_sms_list);

        Uri uri = Uri.parse("content://sms");

        String[] projection = new String[] { "body" };
        try {
            managedCursor = managedQuery(uri, projection, // Which columns to
                    // return
                    null, // Which rows to return (all rows)
                    null, // Selection arguments (none)
                    null);
            listAlias = new ArrayList<String>();
            listKey = new ArrayList<String>();
            DatabaseProvider dp = new DatabaseProvider(new DatabaseConnection(this));
            if (managedCursor.moveToFirst()) {
                do {
                    String body = managedCursor.getString(0);
                    if (body.contains("#@ErgoSum#@ ")) {

                        String url = body.substring(body
                                .lastIndexOf("#@ErgoSum#@ ") + 12);

                        if (url.contains(" ")) {

                            String code = url.substring(0, url.indexOf(' '));

                            String alias = "Inconnu";
                            if (url.length() > code.length()) {
                                alias = url.substring(code.length() + 1);
                            }
                            dp.open();
                            if (!dp.hasContact(code)) {
                                listAlias.add(alias);
                                listKey.add(code);
                            }
                            dp.close();
                        }
                    }
                } while (managedCursor.moveToNext());
            }
        } catch (SecurityException e) {
            Log.e("ergoSum", "You haven't the permission to access to SMS", e);
        }
        mAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_multiple_choice,
                android.R.id.text1, listAlias);
        setListAdapter(mAdapter);
        final ListView listView = getListView();

        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        // new SimpleCursorAdapter(SmsList.this,
        // android.R.layout.simple_list_item_1, managedCursor, null, new int[]
        // {android.R.id.text1}));

    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        if (l.isItemChecked(position)) {

            final String alias = listAlias.get(position);
            final String key = listKey.get(position);
            // final int pos = position;
            final ProgressDialog mProgressDialog = new ProgressDialog(
                    AddContactSMSMailActivity.this);
            final Thread mThread = new Thread() {
                public void run() {
                    RemoteProvider dao = new RemoteProvider(new DatabaseConnection(
                            AddContactSMSMailActivity.this));
                    if (dao.addContact(key, alias) == null)
                        mHandler.post(invalidContact);
                    else {
                        mHandler.post(regenList);
                        AddContactSMSMailActivity.this.setResult(RESULT_OK);
                    }
                    // list.remove(pos);
                    mProgressDialog.dismiss();
                }
            };
            // mProgressDialog.setIcon(R.drawable.alert_dialog_icon);
            mProgressDialog.setTitle(R.string.add_contact_wait_url);
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setButton2(getText(R.string.dialog_cancel),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            mThread.stop();
                            mProgressDialog.dismiss();
                            /* User clicked No so do some stuff */
                        }
                    });
            mProgressDialog.show();
            mThread.start();
        }
        super.onListItemClick(l, v, position, id);
        l.setItemChecked(position, true);
    }
}
